<?php
use \GatewayWorker\Lib\Gateway;


class cmd_enterroom extends cmdbase
{
	public function onCmd($msg){
		$group_mgr = $GLOBALS['GroupMgr'];

		$group_id = $msg->group_id;
		$user_id = $this->getCurUid();
		$room_num = Gateway::getClientCountByGroup($group_id);

		$msg_rsp = new enterroom_rsp();

		if($room_num < 1){
			//不存在此房间
			$msg_rsp->ret = NetErrorCode::Error;
			$msg_rsp->reason = "无此房间，或里面的人都离线了";
			return $msg_rsp;
		}else if($room_num > (cmd_createroom::$MaxNum - 1)){
			//房间人数过多
			$msg_rsp->ret = NetErrorCode::Error;
			$msg_rsp->reason = "房间人数过多:$room_num";
			return $msg_rsp;
		}else{
			//房间人数（包括离线）过多
			$count_online = $group_mgr->getSplMemberInfoCount($group_id);
			if($count_online > (cmd_createroom::$MaxNum - 1)){
				$infos = $group_mgr->getSplMemberInfos($group_id);
				$is_enter_room = false;
				foreach ($infos as $info) {
					if($info->uid == $user_id){
						$is_enter_room = true;
						break;
					}
				}
				if(!$is_enter_room){
					$msg_rsp->ret = NetErrorCode::Error;
					$msg_rsp->reason = "房间所有人数过多:$count_online";
					return $msg_rsp;
				}
			}
		}



		//广播
		$member_info = new member_info();
		$member_info->uid = $user_id;
		$member_info->name = ClientMgr::getNameByUid($user_id);
		//跨服数据读取
		$is_entered_room = $group_mgr->writeMemberInfo($member_info, $group_id);
		$notify_enterroom = new notify_enterroom();
		$notify_enterroom->member = $member_info;
		Events::sendToGroup($group_id, notify_enterroom::class, $notify_enterroom);

		
		//加入组(这样 notify_enterroom 当前客户端就不会收到了，节省宽带)
		$group_mgr->joinGroup($group_id);

		//返回消息
		$member_infos = array();
		$uid_list = Gateway::getUidListByGroup($group_id);
		foreach ($uid_list as $uid) {
			$member_info = new member_info();
			$member_info->uid = $uid;
			$member_info->name = ClientMgr::getNameByUid($uid);

			//跨服数据读取
			$group_mgr->writeMemberInfo($member_info, $group_id);
			
			
			$member_infos[] = $member_info;
		}
		$msg_rsp->ret = NetErrorCode::None;
		$msg_rsp->group_id = $group_id;
		$msg_rsp->member_infos = $member_infos;

		//存跨服数据
		if(!$is_entered_room){
			//没有进过房间
			$group_mgr->storeSlpMemberInfo($user_id, $group_id, CardType::Invalid, SupportType::Invalid);
		}

 		return $msg_rsp;
	}

}